package admin

import (
	"chaowan/data_source"
	"chaowan/models"
	"chaowan/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"reflect"
	"strconv"
	"time"
)

var (
	defaultSheetName = "Sheet1" //默认Sheet名称
	defaultHeight    = 25.0     //默认行高度
)

type lzExcelExport struct {
	file      *excelize.File
	sheetName string //可定义默认sheet名称
}

func NewMyExcel() *lzExcelExport {
	return &lzExcelExport{file: createFile(), sheetName: defaultSheetName}
}

// 导出基本的表格
func (l *lzExcelExport) ExportToPath(params []map[string]string, data []map[string]interface{}, path string) (string, error) {
	l.export(params, data)
	name := createFileName()
	filePath := path + "/" + name
	err := l.file.SaveAs(filePath)
	return filePath, err
}

// 导出到浏览器。此处使用的gin框架 其他框架可自行修改ctx
func (l *lzExcelExport) ExportToWeb(params []map[string]string, data []map[string]interface{}, c *gin.Context) {
	l.export(params, data)
	buffer, _ := l.file.WriteToBuffer()
	//设置文件类型
	c.Header("Content-Type", "application/vnd.ms-excel;charset=utf8")
	//设置文件名称
	c.Header("Content-Disposition", "attachment; filename="+url.QueryEscape(createFileName()))
	_, _ = c.Writer.Write(buffer.Bytes())
}

// 设置首行
func (l *lzExcelExport) writeTop(params []map[string]string) {
	topStyle, _ := l.file.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{
			Horizontal: "center",
		},
		Font: &excelize.Font{
			Family: "宋体",
			Size:   10,
		},
	})
	var word = 'A'
	//首行写入
	for _, conf := range params {
		title := conf["title"]
		width, _ := strconv.ParseFloat(conf["width"], 64)
		line := fmt.Sprintf("%c1", word)
		//设置标题
		_ = l.file.SetCellValue(l.sheetName, line, title)
		//列宽
		_ = l.file.SetColWidth(l.sheetName, fmt.Sprintf("%c", word), fmt.Sprintf("%c", word), width)
		//设置样式
		_ = l.file.SetCellStyle(l.sheetName, line, line, topStyle)
		word++
	}
}

// 写入数据
func (l *lzExcelExport) writeData(params []map[string]string, data []map[string]interface{}) {
	lineStyle, _ := l.file.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{
			Horizontal: "center",
		},
		Font: &excelize.Font{
			Family: "宋体",
			Size:   10,
		},
	})
	//数据写入
	var j = 2 //数据开始行数
	for i, val := range data {
		//设置行高
		_ = l.file.SetRowHeight(l.sheetName, i+1, defaultHeight)
		//逐列写入
		var word = 'A'
		for _, conf := range params {
			valKey := conf["key"]
			line := fmt.Sprintf("%c%v", word, j)
			isNum := conf["is_num"]

			//设置值
			if isNum != "0" {
				valNum := fmt.Sprintf("'%v", val[valKey])
				_ = l.file.SetCellValue(l.sheetName, line, valNum)
			} else {
				_ = l.file.SetCellValue(l.sheetName, line, val[valKey])
			}

			//设置样式
			_ = l.file.SetCellStyle(l.sheetName, line, line, lineStyle)
			word++
		}
		j++
	}
	//设置行高 尾行
	_ = l.file.SetRowHeight(l.sheetName, len(data)+1, defaultHeight)
}

func (l *lzExcelExport) export(params []map[string]string, data []map[string]interface{}) {
	l.writeTop(params)
	l.writeData(params, data)
}

func createFile() *excelize.File {
	f := excelize.NewFile()
	// 创建一个默认工作表
	sheetName := defaultSheetName
	index, _ := f.NewSheet(sheetName)
	// 设置工作簿的默认工作表
	f.SetActiveSheet(index)
	return f
}

func createFileName() string {
	name := time.Now().Format("2006-01-02-15-04-05")
	rand.Seed(time.Now().UnixNano())
	return fmt.Sprintf("excle-%v-%v.xlsx", name, rand.Int63n(time.Now().Unix()))
}

// excel导出(数据源为Struct) []interface{}
func (l *lzExcelExport) ExportExcelByStruct(titleList []string, data []interface{}, fileName string, sheetName string, c *gin.Context) error {
	l.file.SetSheetName("Sheet1", sheetName)
	header := make([]string, 0)
	for _, v := range titleList {
		header = append(header, v)
	}
	rowStyleID, _ := l.file.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{
			Horizontal: "center",
		},
		Font: &excelize.Font{
			Family: "宋体",
			Size:   10,
		},
	})
	_ = l.file.SetSheetRow(sheetName, "A1", &header)
	_ = l.file.SetRowHeight("Sheet1", 1, 30)
	length := len(titleList)
	headStyle := Letter(length)

	//return
	var lastRow string
	var widthRow string
	for k, v := range headStyle {

		if k == length-1 {

			lastRow = fmt.Sprintf("%s1", v)
			widthRow = v
		}
	}
	if err := l.file.SetColWidth(sheetName, "A", widthRow, 30); err != nil {
		fmt.Print("错误--", err.Error())
	}
	rowNum := 1
	for _, v := range data {

		t := reflect.TypeOf(v)
		fmt.Print("--ttt--", t.NumField())
		value := reflect.ValueOf(v)
		row := make([]interface {
		}, 0)
		for l := 0; l < t.NumField(); l++ {

			val := value.Field(l).Interface()
			row = append(row, val)
		}
		rowNum++
		err := l.file.SetSheetRow(sheetName, "A"+strconv.Itoa(rowNum), &row)
		_ = l.file.SetCellStyle(sheetName, fmt.Sprintf("A%d", rowNum), fmt.Sprintf("%s", lastRow), rowStyleID)
		if err != nil {
			return err
		}
	}
	disposition := fmt.Sprintf("attachment; filename=%s.xlsx", url.QueryEscape(fileName))
	c.Writer.Header().Set("Content-Type", "application/octet-stream")
	c.Writer.Header().Set("Content-Disposition", disposition)
	c.Writer.Header().Set("Content-Transfer-Encoding", "binary")
	c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Disposition")
	return l.file.Write(c.Writer)
}

// Letter 遍历a-z
func Letter(length int) []string {
	var str []string
	for i := 0; i < length; i++ {
		str = append(str, string(rune('A'+i)))
	}
	return str
}

func rands(min, max float32) float64 {
	max = max - min
	rand.Seed(time.Now().UnixNano()) //设置随机种子，使每次结果不一样
	res := Round2(float64(min+max*rand.Float32()), 2)
	return res
}
func Round2(f float64, n int) float64 {
	floatStr := fmt.Sprintf("%."+strconv.Itoa(n)+"f", f)
	inst, _ := strconv.ParseFloat(floatStr, 64)
	return inst
}

func Jisuanceshi(ctx *gin.Context) {
	mo := 50 / 6

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    mo,
		"msg":     "ok",
	})
	return
}

func Choujianggooddr(ctx *gin.Context) {
	files, _ := ctx.FormFile("file")
	otherid := ctx.PostForm("otherid")
	state := ctx.PostForm("state")
	unix_int := time.Now().Unix()                    // 时间戳，int类型
	time_unix_str := strconv.FormatInt(unix_int, 10) // 讲int类型转为string类型，方便拼接，使用sprinf也可以

	file_path := "upload/excel/" + time_unix_str + files.Filename
	ctx.SaveUploadedFile(files, file_path)
	xlsx, err := excelize.OpenFile(file_path)

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	// 获取excel中具体的列的值
	sheets := xlsx.GetSheetList()
	rows, _ := xlsx.GetRows(sheets[0])

	if len(rows) == 0 {
		rows1, _ := xlsx.GetRows(sheets[0])
		rows = rows1
	}
	if state == "1" {
		var niudangoods []models.Niudangood

		for key, row := range rows {
			if key == 0 {
				continue
			}
			niudangood := models.Niudangood{
				Goodid:   utils.StrToInt64(row[0]),
				Niudanid: utils.StrToInt64(otherid),
				Classify: utils.StrToInt64(row[2]),
				Num:      utils.StrToInt64(row[1]),
			}
			niudangoods = append(niudangoods, niudangood)
		}
		Try(func() {
			data_source.Db.Create(&niudangoods)
		}, func(err interface{}) {
			fmt.Printf("------程序执行发生异常-------: %v\n", err)
		})
	}
	if state == "2" {
		var fanshanggoods []models.Fanshanggood
		for key, row := range rows {
			if key == 0 {
				continue
			}
			fanshanggood := models.Fanshanggood{
				Goodid:     utils.StrToInt64(row[0]),
				Fanshangid: utils.StrToInt64(otherid),
				Classify:   utils.StrToInt64(row[2]),
				Num:        utils.StrToInt64(row[1]),
			}
			fanshanggoods = append(fanshanggoods, fanshanggood)
		}
		Try(func() {
			data_source.Db.Create(&fanshanggoods)
		}, func(err interface{}) {
			fmt.Printf("------程序执行发生异常-------: %v\n", err)
		})
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Try(userFn func(), catchFn func(err interface{})) {
	defer func() {
		if err := recover(); err != nil {
			catchFn(err)
		}
	}()

	userFn()
}

type ExcelFanshangcsdcRBody struct {
	Goodid    int64   `json:"goodid" gorm:"goodid"`
	Goodname  string  `json:"goodname" gorm:"goodname"`
	Goodprice float64 `json:"goodprice" gorm:"goodprice"`
	Num       int64   `json:"num" gorm:"num"`
	Dengji    int64   `json:"dengji" gorm:"dengji"`
	State     string  `json:"state" gorm:"state"`
}

func Fanshangcsdc(ctx *gin.Context) {
	fanshangid := ctx.Query("fanshangid")

	var ceshis []models.Orderfanshanggoodcs
	data_source.Db.Where("fanshangid = ?", fanshangid).Find(&ceshis)
	//fmt.Println(users)
	//return
	titles := []string{"商品ID", "商品名称", "商品价格", "数量", "等级（1a赏2b赏3c赏4d赏）", "类型"}

	ex := NewMyExcel()

	var datas []interface{}
	for _, t := range ceshis {

		leixing := "商品"
		if t.State == 2 {
			leixing = "积分"
		} else if t.State == 3 {
			leixing = "赏券"
		}
		datas = append(datas, ExcelFanshangcsdcRBody{
			Goodid:    t.Goodid,
			Goodname:  t.Goodname,
			Goodprice: t.Goodprice,
			Num:       t.Num,
			Dengji:    t.Dengji,
			State:     leixing,
		})
	}

	ex.ExportExcelByStruct(titles, datas, "记录导出", "一番赏", ctx)

}

func Niudancsdc(ctx *gin.Context) {
	niudanid := ctx.Query("niudanid")

	var ceshis []models.Orderniudangoodcs
	data_source.Db.Where("niudanid = ?", niudanid).Find(&ceshis)
	//fmt.Println(users)
	//return
	titles := []string{"商品ID", "商品名称", "商品价格", "数量", "等级（1a赏2b赏3c赏4d赏）", "类型"}

	ex := NewMyExcel()

	var datas []interface{}
	for _, t := range ceshis {

		leixing := "商品"
		if t.State == 2 {
			leixing = "积分"
		} else if t.State == 3 {
			leixing = "赏券"
		}
		datas = append(datas, ExcelFanshangcsdcRBody{
			Goodid:    t.Goodid,
			Goodname:  t.Goodname,
			Goodprice: t.Goodprice,
			Num:       t.Num,
			Dengji:    t.Dengji,
			State:     leixing,
		})
	}

	ex.ExportExcelByStruct(titles, datas, "记录导出", "扭蛋机", ctx)

}

type FanshangorderdcRBody struct {
	Addtime   string  `json:"addtime" gorm:"addtime"`
	Orderno   string  `json:"orderno" gorm:"orderno"`
	Paystatus string  `json:"paystatus" gorm:"paystatus"` // 1微信 2支付宝 3矿石 4微信小程序 5积分
	Price     float64 `json:"price" gorm:"price"`
	Name      string  `json:"name" gorm:"name"`
	Phone     string  `json:"phone" gorm:"phone"`       // 手机号
	Nickname  string  `json:"nickname" gorm:"nickname"` // 昵称
	Laiyuan   string  `json:"laiyuan" gorm:"laiyuan"`
}

func Fanshangorderdc(ctx *gin.Context) {
	inttime := ctx.Query("inttime")
	endtime := ctx.Query("endtime")

	if inttime == "" || endtime == "" {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    "请选择时间进行导出",
			"msg":     "ok",
		})
		return
	}
	var users []models.Orderfanshangsql
	res := data_source.Db.Model(&models.Orderfanshang{}).Select("orderfanshang.*, fanshang.name, fanshang.image, user.phone, user.nickname, user.laiyuan").Joins("left join fanshang on fanshang.id = orderfanshang.fanshangid").Joins("left join user on user.id = orderfanshang.uid").Where("orderfanshang.status = 2").Where("orderfanshang.addtime >= ?", inttime).Where("orderfanshang.addtime < ?", endtime)
	res.Order("id desc").Find(&users)

	titles := []string{"下单时间", "订单号", "支付方式", "价格", "一番赏名称", "下单人电话", "下单人", "渠道"}

	ex := NewMyExcel()
	var datas []interface{}
	for _, t := range users {
		addtime := time.Unix(t.Addtime, 0).Format("2006-01-02 15:04:05")
		paystatus := "微信" // 1微信 2支付宝 3矿石 4微信小程序 5积分
		if t.Paystatus == 1 {
			paystatus = "微信"
		} else if t.Paystatus == 2 {
			paystatus = "支付宝"
		} else if t.Paystatus == 3 {
			paystatus = "矿石"
		} else if t.Paystatus == 4 {
			paystatus = "微信小程序"
		} else if t.Paystatus == 5 {
			paystatus = "积分"
		}
		var laiyuan string
		if t.Laiyuan == 1 {
			laiyuan = "自己推广"
		} else if t.Laiyuan == 2 {
			laiyuan = "小程序广告"
		}
		datas = append(datas, FanshangorderdcRBody{
			Addtime:   addtime,
			Orderno:   t.Orderno,
			Paystatus: paystatus,
			Price:     t.Price,
			Name:      t.Name,
			Phone:     t.Phone,
			Nickname:  t.Nickname,
			Laiyuan:   laiyuan,
		})
	}
	ex.ExportExcelByStruct(titles, datas, "一番赏订单导出", "用户", ctx)
}

func Niudanorderdc(ctx *gin.Context) {
	inttime := ctx.Query("inttime")
	endtime := ctx.Query("endtime")

	if inttime == "" || endtime == "" {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    "请选择时间进行导出",
			"msg":     "ok",
		})
		return
	}
	var users []models.Orderfanshangsql
	res := data_source.Db.Model(&models.Orderniudan{}).Select("orderniudan.*, niudan.name, niudan.image, user.phone, user.nickname, user.laiyuan").Joins("left join niudan on niudan.id = orderniudan.niudanid").Joins("left join user on user.id = orderniudan.uid").Where("orderniudan.status = 2").Where("orderfanshang.addtime >= ?", inttime).Where("orderfanshang.addtime < ?", endtime)
	res.Order("id desc").Find(&users)

	titles := []string{"下单时间", "订单号", "支付方式", "价格", "扭蛋机名称", "下单人电话", "下单人", "渠道"}

	ex := NewMyExcel()
	var datas []interface{}
	for _, t := range users {
		addtime := time.Unix(t.Addtime, 0).Format("2006-01-02 15:04:05")
		paystatus := "微信" // 1微信 2支付宝 3矿石 4微信小程序 5积分
		if t.Paystatus == 1 {
			paystatus = "微信"
		} else if t.Paystatus == 2 {
			paystatus = "支付宝"
		} else if t.Paystatus == 3 {
			paystatus = "矿石"
		} else if t.Paystatus == 4 {
			paystatus = "微信小程序"
		} else if t.Paystatus == 5 {
			paystatus = "积分"
		}
		var laiyuan string
		if t.Laiyuan == 1 {
			laiyuan = "自己推广"
		} else if t.Laiyuan == 2 {
			laiyuan = "小程序广告"
		}
		datas = append(datas, FanshangorderdcRBody{
			Addtime:   addtime,
			Orderno:   t.Orderno,
			Paystatus: paystatus,
			Price:     t.Price,
			Name:      t.Name,
			Phone:     t.Phone,
			Nickname:  t.Nickname,
			Laiyuan:   laiyuan,
		})
	}
	ex.ExportExcelByStruct(titles, datas, "扭蛋机订单导出", "用户", ctx)
}
